package cn.cdeden.aiqa.service.impl;

import cn.cdeden.aiqa.domain.WikiHelperUser;
import cn.cdeden.aiqa.domain.WikiRecord;
import cn.cdeden.aiqa.domain.bo.ChatGptHelperdQueryParam;
import cn.cdeden.aiqa.domain.bo.ChatgptQuestionUserDto;
import cn.cdeden.aiqa.mapper.WikiHelperUserMapper;
import cn.cdeden.aiqa.mapper.WikiRecordMapper;
import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.exception.ServiceException;
import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.StringUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.mybatis.core.page.PageQuery;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import cn.cdeden.aiqa.domain.bo.WikiHelperBo;
import cn.cdeden.aiqa.domain.vo.WikiHelperVo;
import cn.cdeden.aiqa.domain.WikiHelper;
import cn.cdeden.aiqa.mapper.WikiHelperMapper;
import cn.cdeden.aiqa.service.IWikiHelperService;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Objects;

/**
 * 智能体管理Service业务层处理
 *
 * @author Nick
 * @date 2025-02-13
 */
@RequiredArgsConstructor
@Service
public class WikiHelperServiceImpl implements IWikiHelperService {

    private final WikiHelperMapper baseMapper;

    private final WikiHelperUserMapper helperUserMapper;

    private final WikiRecordMapper recordMapper;

    /**
     * 查询智能体管理
     *
     * @param id 主键
     * @return 智能体管理
     */
    @Override
    public WikiHelperVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询智能体管理列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 智能体管理分页列表
     */
    @Override
    public TableDataInfo<WikiHelperVo> queryPageList(WikiHelperBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WikiHelper> lqw = buildQueryWrapper(bo);
        Page<WikiHelperVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的智能体管理列表
     *
     * @param bo 查询条件
     * @return 智能体管理列表
     */
    @Override
    public List<WikiHelperVo> queryList(WikiHelperBo bo) {
        LambdaQueryWrapper<WikiHelper> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<WikiHelper> buildQueryWrapper(WikiHelperBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<WikiHelper> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTitleText()), WikiHelper::getTitleText, bo.getTitleText());
        lqw.eq(StringUtils.isNotBlank(bo.getBgColor()), WikiHelper::getBgColor, bo.getBgColor());
        lqw.eq(StringUtils.isNotBlank(bo.getFontColor()), WikiHelper::getFontColor, bo.getFontColor());
        lqw.like(StringUtils.isNotBlank(bo.getTitleName()), WikiHelper::getTitleName, bo.getTitleName());
        lqw.eq(StringUtils.isNotBlank(bo.getDesc()), WikiHelper::getDesc, bo.getDesc());
        lqw.eq(StringUtils.isNotBlank(bo.getCommand()), WikiHelper::getCommand, bo.getCommand());
        lqw.eq(StringUtils.isNotBlank(bo.getExample()), WikiHelper::getExample, bo.getExample());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), WikiHelper::getType, bo.getType());
        return lqw;
    }

    /**
     * 新增智能体管理
     *
     * @param bo 智能体管理
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(WikiHelperBo bo) {
        WikiHelper add = MapstructUtils.convert(bo, WikiHelper.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改智能体管理
     *
     * @param bo 智能体管理
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(WikiHelperBo bo) {
        WikiHelper update = MapstructUtils.convert(bo, WikiHelper.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(WikiHelper entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除智能体管理信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 给用户添加助手
     * @param questionUserDto
     */
    @Override
    public void addHelper(ChatgptQuestionUserDto questionUserDto) {
        WikiHelperUser chatgptQuestionUser = helperUserMapper.selectOne(new LambdaQueryWrapper<WikiHelperUser>()
            .eq(WikiHelperUser::getUserId, questionUserDto.getUserId())
            .eq(WikiHelperUser::getAssistantId, questionUserDto.getAssistantId()));

        if(!Objects.isNull(chatgptQuestionUser)){
            throw new ServiceException("当前助手已添加");
        }
        helperUserMapper.insert(BeanUtil.toBean(questionUserDto,WikiHelperUser.class));

    }

    /**
     * 给用户去除助手
     * @param questionUserDto
     */
    @Override
    public void delHelper(ChatgptQuestionUserDto questionUserDto) {
        helperUserMapper.delete(new LambdaQueryWrapper<WikiHelperUser>()
            .eq(WikiHelperUser::getUserId, questionUserDto.getUserId())
            .eq(WikiHelperUser::getAssistantId, questionUserDto.getAssistantId()));
        //去除用户助手的同时删除与助手的聊天记录
        recordMapper.delete(new LambdaQueryWrapper<WikiRecord>()
            .eq(WikiRecord::getUserId, questionUserDto.getUserId())
            .eq(WikiRecord::getAssistantId, questionUserDto.getAssistantId()));

    }

    @Override
    public TableDataInfo<WikiHelperVo> select(ChatGptHelperdQueryParam query, Pageable pageable) {
        IPage<WikiHelper> page = new Page<WikiHelper>(pageable.getPageNumber() + 1, pageable.getPageSize());
        IPage<WikiHelperVo> result = baseMapper.selectAll(page, query);

        return TableDataInfo.build(result);
    }

    @Override
    public R<List<WikiHelperVo>> selectAll(ChatGptHelperdQueryParam query) {
        List<WikiHelperVo> chatGptHelperVos = baseMapper.selectAllList(query);
        return R.ok(chatGptHelperVos);
    }
}
